package sskj.regulatory.presentation.screen.home

import com.google.gson.JsonParser
import com.google.gson.JsonSyntaxException
import isskj.regulatory.presentation.base_mvp.api.ApiPresenter
import sskj.regulatory.data.response.session.BingDingResponse
import sskj.regulatory.di.scope.PerActivity
import javax.inject.Inject


@PerActivity
class HomePresenter @Inject constructor()
    : ApiPresenter<HomeContract.View>(), HomeContract.Presenter {


    override fun onRequestError(errorCode: String?, errorMessage: String?) {
        super.onRequestError(errorCode, errorMessage)
        view.hideLoading()
        view.showError(errorMessage)
    }

    override fun qrLogin(qrText: String) {

        try {
            val jsonObject = JsonParser().parse(qrText).asJsonObject

            fetch(userInteractor.getIndexData()) {

                when (jsonObject.get("type").asString) {
                    "XMB" -> {
                        val xmb: BingDingResponse? = it.getBingDingByRole("001")

                        when (xmb) {
                            null -> {
                                view.showNoBingDingRole()
                            }
                            else -> {
                                fetch(userInteractor.xmbQrLogin(jsonObject.get("key").asString, xmb.userName.toString(), xmb.pwd.toString())) {
                                    view.hideLoading()
                                    view.gotoDoQrLogin(jsonObject.get("type").asString, jsonObject.get("key").asString)
                                }
                            }
                        }
                    }
                    else -> {

                    }
                }


            }
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
            view.showError("扫描二维码解析错误。")
        }
    }


    override fun indexData() {

    }
}